<?php
// Lấy một danh sách các entry của user, chỉ định bởi UserId
function getEntriesByUser($user_id = 0)
{
    $sql = "SELECT * 
            FROM entries 
            WHERE UserId = '{$user_id}'";
    if($result = mysqli_query(getDB(), $sql))
    {		
            while($row = mysqli_fetch_assoc($result))
            {
                    return $row;
            }
    }
}
// Lấy một entry, chỉ định bởi EntryId
function getEntryById($entry_id = 0)
{
    $sql = "SELECT * 
            FROM entries 
            WHERE EntryId = '{$entry_id}'";
    if($result = mysqli_query(getDB(), $sql))
    {		
            while($row = mysqli_fetch_assoc($result))
            {
                    return $row;
            }	
    }
}
//
//
function getListEntries($from = 0, $to = 1000)
{
    $sql = "SELECT `entries`.*, `profiles`.`Fullname`, `profiles`.`Avatar` 
            FROM `entries` 
            LEFT JOIN `profiles` 
                ON `entries`.`UserId` = `profiles`.`UserId` 
            ORDER BY `DatePosted` DESC";
    $list = array();

    $result = mysqli_query(getDB(), $sql);
    if($result !== FALSE and mysqli_num_rows($result) > 0)
    {
        while($row = mysqli_fetch_assoc($result))
        {
            $list[] = $row;
        }
    }
    return $list;
}
// Thêm dữ liệu vào bảng entries
 function addEntry($userid, $title, $position, $description)
 {
    $sql = "INSERT INTO `entries` (`UserId`, `Title`, `Position`, `Description`) 
            VALUES ('{$userid}', '{$title}', '{$position}', '{$description}')";
    return mysqli_query(getDB(), $sql);
 }
 
 function getLastEntryByUser($uid = 1)
{
    $sql = "SELECT `entries`.*, `profiles`.`Fullname`, `profiles`.`Avatar` 
            FROM `entries` 
            LEFT JOIN `profiles` 
                ON `entries`.`UserId` = `profiles`.`UserId` 
            WHERE `EntryId` = (SELECT MAX(EntryId) FROM entries WHERE UserId = '{$uid}') LIMIT 1";
    if($result = mysqli_query(getDB(), $sql))
    {
        return mysqli_fetch_assoc($result);
    }
    return null;
}

function vote($entry_id)
{
        // Lấy số lượt vote ban đầu
        $sql = "SELECT `Vote` FROM `entries` WHERE `EntryId`='$entry_id' LIMIT 1";
        $result = mysqli_query(getDB(), $sql);
        $row = mysqli_fetch_assoc($result);
        $num_vote_before = $row['Vote'];

        // Thêm lượt vote
        $num_vote_after = $num_vote_before + 1;
        $sql = "UPDATE `entries` SET `Vote`='$num_vote_after' WHERE `EntryId`='$entry_id'";
        mysqli_query(getDB(), $sql);

        // Gía trị trả về là số lượt vote hiện tại
        $sql = "SELECT * FROM `entries` WHERE `EntryId`='$entry_id' LIMIT 1";
        $result = mysqli_query(getDB(), $sql);
        $row = mysqli_fetch_assoc($result);
        $num_vote_current = $row['Vote'];
        return $num_vote_current;
}
?>
